package com.alma.talk;



import java.util.ArrayList;
import java.util.List;

import org.omg.CORBA.ORB;

import com.alma.MTalk.Talk;
import com.alma.MTalk.TalkOperations;
import com.alma.MTalk.TalkPOATie;


public class TalkImpl implements TalkOperations {
	private static short numeroConv = 0;
	
	private final List<TalkListener> listeners = new ArrayList<TalkListener>();
	private ORB orb;
	Talk instance;
	
	public TalkImpl(ORB orb){
		this.orb = orb;
	}
	
	/**
	 * 
	 * @return L'IOR
	 */
	public String getIOR(){		
		return orb.object_to_string(instance);
	}
	
	@Override
	public void accept(short numConvSideB, short numConvSideA, String talkIor) {
	}

	@Override
	public void deny(short numConvSideA) {
	}

	@Override
	public void talk(short numConvYourSide, String message) {
		onMessage(numConvYourSide, message);
	}

	@Override
	public void stop(short numConvYourSide) {
		onTalkStopped(numConvYourSide);
	}

	/**
	 *  Accepter une conversation et fournir automaquement le numero suivant
	 * @param numConvSideA
	 * @param talkIor
	 */
	public synchronized short accept(short numConvSideA,String talkIor){
		short convId = genId();
		accept(convId,numConvSideA,talkIor);
		return convId;
	}
	
	/**
	 * 
	 * @return L'instance du talk CORBA
	 */
	public Talk getInstance(){
		if(instance==null){			
			TalkPOATie tpt = new TalkPOATie(this);
			instance = tpt._this(orb);
		}
		return instance;
	}
	
	/**
	 * 
	 * @param listener
	 */
	public void addListener(TalkListener listener){		
		if(listener!=null) listeners.add(listener);
	}
	
	/**
	 * 
	 * @param listener
	 */
	public void removeListener(TalkListener listener){
		if(listener!=null) listeners.remove(listener);
	}
	
	/**
	 * 
	 * @param id
	 * @param msg
	 */
	private void onMessage(short id,String msg){		
		synchronized(listeners){
			for(TalkListener listener : listeners){
				listener.onMessage(id, msg);
			}
		}
	}
	
	/**
	 * 
	 * @param id
	 */
	private void onTalkStopped(short id){		
		synchronized(listeners){
			for(TalkListener listener : listeners){
				listener.onStop(id);
			}
		}
	}
	
	private synchronized static short genId(){
		return numeroConv++;
	}
}
